package api

import (
	"github.com/gin-gonic/gin"
	"zsc-boot/app/message/model"
	"zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type MessageApi struct {
}

// List 列表
func (m *MessageApi) List(ctx *gin.Context) {
	var req core.PageInfo
	_ = ctx.Bind(&req)

	userId := service.GetUserID(ctx)

	var (
		list  []model.Message
		count int64
	)
	if err := orm.GetDb().Model(&model.Message{}).
		Where("receiver_id = ?", userId).Count(&count).Error; err != nil {
		web.FailResponse(ctx, err, "消息拉取异常")
		return
	}

	if err := orm.GetDb().Model(&model.Message{}).Where("receiver_id = ? and is_read = ?", userId, false).
		Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Preload("SenderInfo").
		Preload("ReceiverInfo").Find(&list).Error; err != nil {
		web.FailResponse(ctx, err, "消息拉取异常")
		return
	}

	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

// BatchIsRead 批量已读
func (m *MessageApi) BatchIsRead(ctx *gin.Context) {
	var req core.IdsReq
	_ = ctx.Bind(&req)

	if err := orm.GetDb().Model(&model.Message{}).
		Where("id in ?", req.Ids).Update("is_read", true).Error; err != nil {
		web.FailResponse(ctx, err, "操作异常")
		return
	}
	web.SuccessResponse(ctx, nil)
}
